//
//  ViewController.m
//  IPCamera
//
//  Created by 宣佚 on 15/5/28.
//  Copyright (c) 2015年 宣佚. All rights reserved.
//

#import "LinkViewController.h"
#import <ActionSheetPicker-3.0/ActionSheetPicker.h>
#import <MLPAutoCompleteTextField/MLPAutoCompleteTextField.h>
#import <MLPAutoCompleteTextField/MLPAutoCompleteTextFieldDataSource.h>
#import <MLPAutoCompleteTextField/MLPAutoCompleteTextFieldDelegate.h>
#import <QuartzCore/QuartzCore.h>
#import "Andon_TUTK.h"
#import "LinkBL.h"
#import "LXYQRCodeViewController.h"
#import "VideoControlCenterViewController.h"
#import "DOPNavbarMenu.h"

#define MENU_POPOVER_FRAME  CGRectMake(10, 64, 100, 88)

@interface LinkViewController () <UITextFieldDelegate,MLPAutoCompleteTextFieldDataSource, MLPAutoCompleteTextFieldDelegate,DOPNavbarMenuDelegate,TUTKClientDelegate>
{
    Andon_TUTK *tutkclient;
}
/**
 *  UI控件
 */
@property (weak, nonatomic) IBOutlet UITextField *LinkTypeField;
@property (weak, nonatomic) IBOutlet MLPAutoCompleteTextField *DeviceIDField;
@property (weak, nonatomic) IBOutlet UITextField *UserNameField;
@property (weak, nonatomic) IBOutlet UITextField *PassWordField;
@property (weak, nonatomic) IBOutlet UILabel *AudioFormatLabel;
@property (weak, nonatomic) IBOutlet UIButton *LinkBut;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *menuBut;

/**
 *  连接类型
 *  -TUTK
 *  -GOOLINK
 */
@property (assign, nonatomic) ENUM_LINKTYPE LinkType;

/**
 *  设置音频格式
*   -AAC
*   -G711A
 *  -PCM
 */
@property (assign, nonatomic) ENUM_AUDIO_FORMAT audioFormat;

/**
 *  是否已经连接上
 */
@property (assign, nonatomic) BOOL isLinking;

@property (strong, nonatomic) DOPNavbarMenu *menu;
@property (assign, nonatomic) NSInteger numberOfItemsInRow;
@end

@implementation LinkViewController

#pragma mark - life cycle

    //设置了自定义导航栏标题
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    //设置自定义导航标题视图
    UILabel *label = [[BD_CustomNavigationBar sharedHandler] CustomNavigationTitle:@"IPCamera"];
    self.navigationItem.titleView = label;
}

    //初始化连接状态变量和音频格式选择
    //以及菜单按钮tag
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    //设置了连接类型的默认值
    self.LinkType = LINKTYPE_TUTK;
    self.LinkTypeField.text = @"TUTK";
    
    self.isLinking = NO;
    self.menuBut.tag = 0;
    self.audioFormat = AUDIO_FORMAT_G711A;
}

    //设置用户名和密码以及下弹菜单中项目的个数
    //并更新音频格式选择
-(void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];
    self.UserNameField.text = @"admin";
    self.PassWordField.text = @"admin";

    self.numberOfItemsInRow = 3;
    [self changeAudioFormat];
}


-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"ShowVideoPush"]) {
        VideoControlCenterViewController *vc = (VideoControlCenterViewController *)segue.destinationViewController;
        vc.linkType = self.LinkType;
        vc.DeviceID = self.DeviceIDField.text;
        vc.avIndex = [sender intValue];
        vc.tutkclient = tutkclient;
        vc.audioFormat = self.audioFormat;
        [MBProgressHUD hideHUD];
    }
}

#pragma mark - UITextFieldDelegate

    //设置LinkTypeTextField为不可编辑状态
    //其它textField为可编辑状态
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    if (textField == self.LinkTypeField) {
        return NO;
    }
    else {
        return YES;
    }
}

    //设置按控件摆放顺序来输入内容，并在最后一个textField输入完成后，直接触发"连接设备"按钮
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField == self.DeviceIDField) {
        [self.DeviceIDField resignFirstResponder];
        [self.UserNameField becomeFirstResponder];
    }
    else if (textField == self.UserNameField) {
        [self.UserNameField resignFirstResponder];
        [self.PassWordField becomeFirstResponder];
    }
    else if (textField == self.PassWordField) {
        [self CancelKeyboard:nil];
        [self LinkDeviceButPress:nil];
    }
    return YES;
}

#pragma mark - CustomDelegate

#pragma mark - MLPAutoCompleteTextField
#pragma mark DataSource

    //从LinkType对应的plist文件中读出相应的可用设备的编号，并作为自己实例信息返回
-(NSArray *)autoCompleteTextField:(MLPAutoCompleteTextField *)textField possibleCompletionsForString:(NSString *)string
{
    NSMutableArray *data = [[PlistFileManage sharedHandler] readDeviceList:self.LinkType];
    return data;
}

#pragma mark Delegate

- (BOOL)autoCompleteTextField:(MLPAutoCompleteTextField *)textField
          shouldConfigureCell:(UITableViewCell *)cell
       withAutoCompleteString:(NSString *)autocompleteString
         withAttributedString:(NSAttributedString *)boldedString
        forAutoCompleteObject:(id<MLPAutoCompletionObject>)autocompleteObject
            forRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

#pragma mark - TUTKClientDelegate

-(void)Tutk_StartConnection
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [MBProgressHUD showMessage:@"TUTK开始连接"];
        self.isLinking = NO;
    });
}

-(void)Tutk_Connected_Success:(int)avIndex
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [MBProgressHUD hideHUD];
        [MBProgressHUD showSuccess:@"TUTK连接成功"];
        self.isLinking = YES;
        [self performSegueWithIdentifier:@"ShowVideoPush" sender:[NSNumber numberWithInt:avIndex]];
    });
}

-(void)Tutk_Connected_Failure:(NSString *)errorMessage
{
    dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@"TUTK连接失败:%@",errorMessage);
        [tutkclient stop];
        [MBProgressHUD hideHUD];
        [MBProgressHUD showError:@"TUTK连接失败"];
        self.isLinking = NO;
    });
}

-(void)Tutk_DisConnected_Success
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [MBProgressHUD hideHUD];
        [MBProgressHUD showInfo:@"TUTK断开成功"];
        self.isLinking = NO;
    });
}

#pragma mark - Andon_GooLinkDelegate

-(void)onConnecting{
    dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@"GooLink_StartConnection");
        [MBProgressHUD showMessage:@"GooLink开始连接"];
        self.isLinking = NO;
    });
}

-(void)onConnected:(int)mode andip:(const char*)ip andport:(unsigned short)port{
    dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@"glk_onConnected");
        [MBProgressHUD hideHUD];
        [MBProgressHUD showSuccess:@"GooLink连接成功"];
        self.isLinking = YES;
        [self performSegueWithIdentifier:@"ShowVideoPush" sender:nil];
    });
}

-(void)onDisconnected:(int)errcode{
    dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@"glk_DisConnected_Success");
        [MBProgressHUD hideHUD];
        [MBProgressHUD showInfo:@"GooLink断开成功"];
        self.isLinking = NO;
    });
}

-(void)onModeChanged:(int)mode andip:(const char*)ip andport:(unsigned short)port{
    NSLog(@"onModeChanged:%d,%s,%d",mode,ip,port);
}

-(void)onAVStreamFormat:(void *)data andlength:(unsigned int)length {
    NSLog(@"onAVStreamFormat");
}

-(void)onVideoDataManu:(const void *)data andlength:(unsigned int)length andframeInfo:(const void *)frameInfo andinfoLength:(unsigned int) infoLength {
    NSLog(@"onVideoDataManu");
}

-(void)onAudioDataManu:(const void *)data andlength:(unsigned int)length andframeInfo:(const void *)frameInfo andinfoLength:(unsigned int) infoLength{
    NSLog(@"onAudioDataManu");
}

-(void)onVideoData:(const void *)data
         andlength:(unsigned int)length
     andframeindex:(unsigned int)frameIndex
      andtimestamp:(unsigned int)timestamp
       andisIFrame:(int)isIFrame
{
    
}

-(void)onAudioData:(const void *)data andlength:(unsigned int)length andtimestamp:(unsigned int)timestamp{
    
}

-(void)onIOCtrlByManu:(const void *)data andlength:(unsigned short)length{
    NSLog(@"onIOCtrlByManu");
}

-(void)onAuthorized:(int)result{
    NSLog(@"onAuthorized");
}

#pragma mark -
#pragma mark MLKMenuPopoverDelegate

- (void)didShowMenu:(DOPNavbarMenu *)menu {
    self.navigationItem.rightBarButtonItem.enabled = YES;
}

- (void)didDismissMenu:(DOPNavbarMenu *)menu {
    self.navigationItem.rightBarButtonItem.enabled = YES;
}

- (void)didSelectedMenu:(DOPNavbarMenu *)menu atIndex:(NSInteger)index {
    switch (index) {
        case 0:
        {
            if ([Helper checkCameraAuthorizationStatus] == YES) {
                LXYQRCodeViewController *qrcodevc = [[LXYQRCodeViewController alloc] init];
                qrcodevc.LXYQRCodeSuncessBlock = ^(LXYQRCodeViewController *aqrvc,NSString *qrString){
                    self.DeviceIDField.text = qrString;
                    [aqrvc dismissViewControllerAnimated:NO completion:nil];
                };
                qrcodevc.LXYQRCodeFailBlock = ^(LXYQRCodeViewController *aqrvc){
                    [MBProgressHUD showError:@"扫描失败"];
                    [aqrvc dismissViewControllerAnimated:NO completion:nil];
                };
                qrcodevc.LXYQRCodeCancleBlock = ^(LXYQRCodeViewController *aqrvc){
                    [aqrvc dismissViewControllerAnimated:NO completion:nil];
                    [MBProgressHUD showInfo:@"扫描被取消"];
                };
                [self presentViewController:qrcodevc animated:YES completion:nil];
                break;
            }
        }
        case 1:
        {
            [self performSegueWithIdentifier:@"SettingWifiPush" sender:nil];
            break;
        }
        case 2:
        {
            [self CancelKeyboard:nil];
            NSMutableArray *typeList = [[NSMutableArray alloc] init];
            [typeList addObject:@"ACC"];
            [typeList addObject:@"G711A"];
            [typeList addObject:@"PCM"];
            
            ActionStringDoneBlock done = ^(ActionSheetStringPicker *picker, NSInteger selectedIndex, id selectedValue) {
                switch (selectedIndex) {
                    case 0:
                        self.audioFormat = AUDIO_FORMAT_AAC;
                        break;
                    case 1:
                        self.audioFormat = AUDIO_FORMAT_G711A;
                        break;
                    case 2:
                        self.audioFormat = AUDIO_FORMAT_PCM;
                        break;
                    default:
                        break;
                }
                [self changeAudioFormat];
            };
            ActionStringCancelBlock cancel = ^(ActionSheetStringPicker *picker) {
            };
            
            [ActionSheetStringPicker showPickerWithTitle:@"选择音频格式" rows:typeList initialSelection:0 doneBlock:done cancelBlock:cancel origin:menu];
            break;
        }
        default:
            break;
    }
}

#pragma mark - event response


    //LinkTypeField TouchDown Action Handler
    //选择连接类型
-(IBAction)ChooseLinkTypeAction:(UITextField *)sender
{
    [self CancelKeyboard:nil];
    NSMutableArray *typeList = [[NSMutableArray alloc] init];
    [typeList addObject:@"TUTK"];
    [typeList addObject:@"GOOLINK"];
    
    ActionStringDoneBlock done = ^(ActionSheetStringPicker *picker, NSInteger selectedIndex, id selectedValue) {
        self.LinkTypeField.text = selectedValue;
        switch (selectedIndex) {
            case 0:
                self.LinkType = LINKTYPE_TUTK;
                break;
            case 1:
                self.LinkType = LINKTYPE_GOOLINK;
                break;
            default:
                break;
        }
    };
    ActionStringCancelBlock cancel = ^(ActionSheetStringPicker *picker) {
    };
    
    [ActionSheetStringPicker showPickerWithTitle:@"选择类型" rows:typeList initialSelection:0 doneBlock:done cancelBlock:cancel origin:sender];
}

    //连接设备按钮处理函数
- (IBAction)LinkDeviceButPress:(id)sender {
    [self CancelKeyboard:nil];
    if (self.isLinking == YES) {//已存在连接需要先关闭
        [MBProgressHUD showInfo:@"请先断开连接"];
    } else { //还没有连接上的情况处理
             //检查各数据字段的有效性，并返回相应的信息提示用户正确输入
        NSString *error = [[LinkBL sharedHandler] CheckLinkInfoTip_LinkType:self.LinkType deviceID:self.DeviceIDField.text username:self.UserNameField.text password:self.PassWordField.text];
        
        if (error == nil) {//所需要的信息输入正确
            
                //将要连接的设备ID存放入设备列表中
                //TODO: 存在的疑问
            /*新设备是否应该在连接成功至少一次后再添加到设备列表中*/
            
            BOOL ret = [[LinkBL sharedHandler] writeDeviceIDToDeivesList:self.DeviceIDField.text linkType:self.LinkType];
            if (ret == NO) {//由于没有选择设备的连接方式，所以就没办法把它记录到相应连接方式的设备列表中
                [MBProgressHUD showError:@"更新设备列表有误"];
            }
            else {
                switch (self.LinkType) {
                    case LINKTYPE_TUTK:
                    {
                        tutkclient = [[Andon_TUTK alloc] init];
                        tutkclient.delegate = self;
                        [tutkclient start:self.DeviceIDField.text userName:self.UserNameField.text passWord:self.PassWordField.text];
                    }
                        break;
                    case LINKTYPE_GOOLINK:
                    {
                            //待添加
                    }
                        break;
                    default:
                        break;
                }
            }
            
        }
        else {
            [MBProgressHUD showError:error];
        }
    }
}
    //收起软键盘
- (IBAction)CancelKeyboard:(id)sender {
    [self.LinkTypeField resignFirstResponder];
    [self.DeviceIDField resignFirstResponder];
    [self.UserNameField resignFirstResponder];
    [self.PassWordField resignFirstResponder];
}


    //toggle 下拉菜单
- (IBAction)ShowDownMenu:(id)sender
{
    self.navigationItem.rightBarButtonItem.enabled = NO;
    if (self.menu.isOpen) {
        [self.menu dismissWithAnimation:YES];
    } else {
        [self.menu showInNavigationController:self.navigationController];
    }
}

    //改变音频格式标签的内容
-(void)changeAudioFormat
{
    switch (self.audioFormat) {
        case AUDIO_FORMAT_AAC: {
            self.AudioFormatLabel.text = @"AAC";
            break;
        }
        case AUDIO_FORMAT_G711A: {
            self.AudioFormatLabel.text = @"G711A";
            break;
        }
        case AUDIO_FORMAT_PCM: {
            self.AudioFormatLabel.text = @"PCM";
            break;
        }
        default: {
            break;
        }
    }
}

#pragma mark - getter and setter
    //创建下拉菜单项
- (DOPNavbarMenu *)menu {
    if (_menu == nil) {
        DOPNavbarMenuItem *qrcode_item = [DOPNavbarMenuItem ItemWithTitle:@"扫一扫" icon:[UIImage imageNamed:@"icon-qrcode"]];
        DOPNavbarMenuItem *wifi_item = [DOPNavbarMenuItem ItemWithTitle:@"设置WIFI" icon:[UIImage imageNamed:@"icon-wifi"]];
        DOPNavbarMenuItem *audio_item = [DOPNavbarMenuItem ItemWithTitle:@"音频格式" icon:[UIImage imageNamed:@"icon-audio"]];
        _menu = [[DOPNavbarMenu alloc] initWithItems:@[qrcode_item,wifi_item,audio_item] width:self.view.dop_width maximumNumberInRow:_numberOfItemsInRow];
        _menu.backgroundColor = [UIColor whiteColor];
        _menu.separatarColor = [UIColor lightGrayColor];
        _menu.delegate = self;
    }
    return _menu;
}

@end
